<template>
  <q-scroll-area ref="AreaRef" :class="classes || ''" :style="areaStyle" :thumb-style="$thumbStyle" :visible="false"
                 class="medoc-layout-page-cls no-margin no-padding relative-position">
    <div :class="topClass || ''" class="medoc-layout-page-top q-pt-md q-pl-md q-pr-md fixed-top full-width">
      <slot name="top"></slot>
      <q-resize-observer :debounce="debounce" @resize="size => onResize(size, 'top')" />
    </div>
    <div class="medoc-layout-page-main overflow-hidden">
      <div class="medoc-layout-page-main-top"></div>
      <slot :mainWidth="mainWidth" name="default"></slot>
      <div v-if="!nonBottom" class="medoc-layout-page-main-bottom"></div>
      <q-resize-observer :debounce="debounce" @resize="size => onResize(size, 'main')" />
    </div>
    <div v-if="!nonBottom" :class="bottomClass || ''"
         class="medoc-layout-page-bottom q-pb-md q-pl-md q-pr-md full-width fixed-bottom">
      <slot name="bottom"></slot>
      <q-resize-observer :debounce="debounce" @resize="size => onResize(size, 'bottom')" />
    </div>
    <teleport v-if="AreaRef" to=".medoc-layout-page-cls">
      <q-inner-loading :showing="loading" class="z-top">
        <q-spinner-ios color="primary" size="3rem" />
      </q-inner-loading>
    </teleport>
  </q-scroll-area>
</template>

<script setup>
import { dom } from 'quasar'
import { isSafeNumeric } from 'src/utils/utils.js'
import { computed, ref, watch } from 'vue'

const props = defineProps({
  loading: Boolean, topClass: String, nonBottom: Boolean, bottomClass: String, maxHeight: [String, Number],
  classes: { type: String, default: 'bg-white' }
})

const bgColor = ref('')
const debounce = ref(0)
const mainWidth = ref(0)
const topHeight = ref(0)
const mainHeight = ref(0)
const areaStyle = ref({})
const AreaRef = ref(null)
const bottomHeight = ref(0)

const AreaMaxHeight = computed(() => {
  const { maxHeight } = props
  if (!maxHeight) return '100%'
  return isSafeNumeric(maxHeight) ? `${maxHeight}px` : maxHeight
})

watch(mainHeight, () => setAreaStyle())

const setAreaStyle = () => {
  if (!AreaRef.value) return
  areaStyle.value.height = `${Math.ceil(mainHeight.value || 0)}px`
  bgColor.value = dom.style(AreaRef.value.$el, 'background-color')
}
const onResize = (size, type) => {
  if (type === 'top') topHeight.value = size.height
  else if (type === 'bottom') bottomHeight.value = size.height
  else {
    mainWidth.value = size.width
    mainHeight.value = size.height
  }
}

</script>
<style lang="scss" scoped>
.q-scrollarea {
  max-height: v-bind(AreaMaxHeight);
}

.medoc-layout-page-top, .medoc-layout-page-bottom {
  z-index: 999;
  background-color: v-bind(bgColor);
}

.medoc-layout-page-main {
  &-top {
    height: v-bind('`${topHeight}px`');
  }

  &-bottom {
    height: v-bind('`${bottomHeight}px`');
  }
}
</style>